from collections import defaultdict
from base_oss import BaseOSS
from config import Config
import oss2

class AliyunOSS(BaseOSS):

    def __init__(self) -> None:
        self.endpoint = Config.ALIYUN_OSS_ENDPOINT 
        self.auth = oss2.Auth(Config.ALIYUN_ACCESS_KEY_ID,Config.ALIYUN_ACCESS_KEY_SECRET)
        self.bucket = oss2.Bucket(self.auth,self.endpoint,Config.ALIYUN_BUCKET_NAME)

    def save_file(self, key, _file) -> defaultdict:
        upload_info = defaultdict(int)

        file_exist = self.bucket.object_exists(key)

        if not file_exist:
            _ = self.bucket.put_object(key,_file)

        upload_info["Uploaded size"] = self.__get_file_size(key)

        return upload_info
    
    def download_file(self, key) -> any:
        return self.bucket.get_object(key).read()
    
    def delete_file(self, key) -> any:
        return self.bucket.delete_object(key)
    
    def get_cdn_url(self, key, expired=120) -> str:
        return super().get_cdn_url(key, expired)
    
    def get_url(self, key, expired=120) -> str:
        url = self.bucket.sign_url("GET",key,expires=expired)
        return url 
    
    def set_object_meta(self, key, content_type):
        self.bucket.update_object_meta(key,{"content-Type":content_type})

    def __get_file_size(self,key):

        file_info = self.bucket.get_object_meta(key)
        return int(file_info.headers["Content-Length"])